<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-02 19:42:06
 * @LastEditTime: 2023-07-04 16:11:14
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Repositories;


use App\Models\Role;
use App\Models\RoleApi;
use App\Models\RoleColumn;
use App\Models\RoleDepartment;
use App\Models\RoleMenu;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class RoleRepository extends Repositories
    {


    public function __construct(Role $model)
        {
        $this->model = $model;
        }

    public function getList()
        {
        return $this->model->get();
        }

    public function delete($ids)
        {
        return $this->model->whereIn("id", $ids)->get()->filter(function ($v)
            {
            $v->delete();
            });
        }

    public function menu($ids)
        {
        // DB::connection()->enableQueryLog();

        // $this->whereIn("id", [5])
        //     ->with(['menu'])
        //     ->get();
        // dd(DB::getQueryLog());
        return $this->getRelatedData("menu", [['id', $ids, "in"]]);
        }

    public function department($ids)
        {
        return $this->getRelatedData('department', [['id', $ids, "in"]]);
        }

    public function table_right_btn($ids)
        {
        return $this->getRelatedData('table_right_btn', [['id', $ids, "in"]]);
        }
    public function column($ids)
        {
        return $this->getRelatedData('column', [['id', $ids, "in"]]);
        }

    public function api($ids)
        {
        return $this->getRelatedData('api', [['id', $ids, "in"]]);
        }
    public function enableApi($data)
        {
        foreach ($data['api_ids'] ?? [] as $k => $v) {
            RoleApi::firstOrCreate(['role_id' => $data['role_id'], 'api_id' => $v]);
            }
        // return $this->saveManyToMany($data['api_ids'] ?? [], $data['role_id'], RoleApi::class, "api_id");
        }
    public function disableApi($data)
        {
        foreach ($data['api_ids'] ?? [] as $k => $v) {
            RoleApi::where(['role_id' => $data['role_id'], 'api_id' => $v])->get()->filter(fn($v) => $v->delete());
            }
        // return $this->saveManyToMany($data['api_ids'] ?? [], $data['role_id'], RoleApi::class, "api_id");
        }
    public function savePermission($data)
        {

        $this->saveManyToMany($data['menu_ids'] ?? [], $data['role_id'], RoleMenu::class);

        $this->saveManyToMany($data['department_ids'] ?? [], $data['role_id'], RoleDepartment::class, "department_id");

        $this->saveManyToMany($data['column_ids'] ?? [], $data['role_id'], RoleColumn::class, "column_id");
        // $this->saveManyToMany($data['api_ids'] ?? [], $data['role_id'], RoleApi::class, "api_id");
        return true;
        }
    }